<template>
  <div class="skills-page">
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane label="技能分类" name="categories">
        <!-- 搜索表单 -->
        <el-card class="search-card" shadow="never">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-input v-model="categorySearchForm.name" placeholder="搜索分类名称" :prefix-icon="Search" clearable />
            </el-col>
            <el-col :span="10">
              <el-button :icon="Search" type="primary" @click="handleCategorySearch">搜索</el-button>
              <el-button :icon="Refresh" @click="resetCategorySearch">重置</el-button>
            </el-col>
          </el-row>
        </el-card>

        <!-- 分类表格 -->
        <el-card shadow="never">
          <div class="table-header">
            <div></div>
            <el-button type="primary" :icon="Plus" @click="handleAddCategory">
              新增分类
            </el-button>
          </div>
          <el-table :data="skillCategories" style="width: 100%" v-loading="categoryLoading">
            <el-table-column type="index" label="序号" min-width="45" />

            <el-table-column prop="name" label="分类名称" min-width="200" />

            <el-table-column prop="description" label="描述" min-width="250" />

            <el-table-column prop="skillCount" label="技能数量" min-width="120" align="center">
              <template #default="{ row }">
                <el-tag size="small" effect="plain">
                  {{ row.skillCount }} 项
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="sortOrder" label="排序" min-width="80" align="center" />

            <el-table-column prop="status" label="状态" min-width="100" align="center">
              <template #default="{ row }">
                <el-switch v-model="row.status" active-value="enabled" inactive-value="disabled"
                  @change="updateCategoryStatus(row)" />
              </template>
            </el-table-column>

            <el-table-column label="操作" min-width="200" fixed="right">
              <template #default="{ row }">
                <div class="action-buttons">
                  <el-button size="small" :icon="Edit" @click="handleEditCategory(row)">
                    编辑
                  </el-button>
                  <el-button size="small" :icon="Delete" type="danger" @click="handleDeleteCategory(row)">
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination">
            <el-pagination v-model:current-page="categoryPagination.page" v-model:page-size="categoryPagination.size"
              :page-sizes="[10, 20, 50, 100]" :total="categoryPagination.total"
              layout="total, sizes, prev, pager, next, jumper" @size-change="handleCategorySizeChange"
              @current-change="handleCategoryCurrentChange" />
          </div>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="所有技能" name="all">
        <!-- 搜索表单 -->
        <el-card class="search-card" shadow="never">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-input v-model="searchForm.name" placeholder="搜索技能名称" :prefix-icon="Search" clearable />
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchForm.category" placeholder="技能分类" clearable>
                <el-option label="全部" value="" />
                <el-option v-for="category in skillCategories" :key="category.id" :label="category.name"
                  :value="category.id" />
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchForm.level" placeholder="熟练度等级" clearable>
                <el-option label="全部" value="" />
                <el-option label="入门" value="入门" />
                <el-option label="初级" value="初级" />
                <el-option label="中级" value="中级" />
                <el-option label="高级" value="高级" />
                <el-option label="专家" value="专家" />
              </el-select>
            </el-col>
            <el-col :span="10">
              <el-button :icon="Search" type="primary" @click="handleSearch">搜索</el-button>
              <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
            </el-col>
          </el-row>
        </el-card>

        <!-- 技能表格 -->
        <el-card shadow="never">
          <div class="table-header">
            <div></div>
            <el-button type="primary" :icon="Plus" @click="handleAddSkill">
              新增技能
            </el-button>
          </div>
          <el-table :data="allSkills" style="width: 100%" v-loading="skillLoading">
            <el-table-column type="index" label="序号" min-width="45" />
            <el-table-column prop="name" label="技能名称" min-width="130" />
            <el-table-column prop="categoryName" label="分类" min-width="100">
              <template #default="{ row }">
                <el-tag :type="getCategoryType(row.categoryName)" size="small">
                  {{ row.categoryName }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="proficiencyLevel" label="熟练度进度" min-width="200">
              <template #default="{ row }">
                <el-progress :percentage="row.proficiencyLevel" :stroke-width="8" />
              </template>
            </el-table-column>
            <el-table-column label="熟练度等级" min-width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getLevelTagType(row.level)" size="small">
                  {{ row.level }} ({{ row.proficiencyLevel }}%)
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" min-width="200" />
            <el-table-column prop="yearsOfExperience" label="经验年数" min-width="100" align="center" />
            <el-table-column prop="status" label="状态" min-width="100" align="center">
              <template #default="{ row }">
                <el-switch v-model="row.status" active-value="enabled" inactive-value="disabled"
                  @change="updateSkillStatus(row)" />
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="200">
              <template #default="{ row }">
                <div class="action-buttons">
                  <el-button size="small" :icon="View" @click="handleViewSkill(row)">
                    查看
                  </el-button>
                  <el-button size="small" :icon="Edit" @click="handleEditSkill(row)">
                    编辑
                  </el-button>
                  <el-button size="small" :icon="Delete" type="danger" @click="handleDeleteSkill(row)">
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination">
            <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.size"
              :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 技能表单弹窗 -->
    <el-dialog v-model="skillFormVisible" :title="skillFormMode === 'add' ? '添加技能' : '编辑技能'" width="600px"
      @close="resetSkillForm">

      <div class="skill-form-content">
        <el-form ref="skillFormRef" :model="skillForm" :rules="skillFormRules" label-width="120px" status-icon>

          <el-form-item label="技能名称" prop="name">
            <el-input v-model="skillForm.name" placeholder="请输入技能名称" maxlength="100" show-word-limit />
          </el-form-item>

          <el-form-item label="技能分类" prop="categoryId">
            <el-select v-model="skillForm.categoryId" placeholder="请选择技能分类" style="width: 100%">
              <el-option v-for="category in skillCategories" :key="category.id" :label="category.name"
                :value="category.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="熟练度" prop="proficiencyLevel">
            <el-slider v-model="skillForm.proficiencyLevel" :min="0" :max="100" :step="1" show-stops show-input
              show-input-controls style="width: 100%" />
          </el-form-item>

          <el-form-item label="经验年数" prop="yearsOfExperience">
            <el-input-number v-model="skillForm.yearsOfExperience" :min="0" :max="50" :step="1" style="width: 100%"
              controls-position="right" />
          </el-form-item>

          <el-form-item label="技能描述" prop="description">
            <el-input v-model="skillForm.description" type="textarea" :rows="3" placeholder="请描述技能的具体内容和应用场景"
              maxlength="500" show-word-limit />
          </el-form-item>

          <el-form-item label="是否为核心技能">
            <el-switch v-model="skillForm.isCore" :active-value="1" :inactive-value="0" active-text="是"
              inactive-text="否" />
          </el-form-item>

          <el-form-item label="状态">
            <el-switch v-model="skillForm.status" active-value="enabled" inactive-value="disabled" active-text="启用"
              inactive-text="禁用" />
          </el-form-item>

        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="skillFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSkillForm">
            {{ skillFormMode === 'add' ? '添加' : '更新' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 技能详情查看弹窗 -->
    <el-dialog v-model="skillDetailVisible" title="技能详情" width="800px" :close-on-click-modal="false">

      <div class="skill-detail-content">
        <!-- 技能标题区域 -->
        <div class="skill-header">
          <div class="skill-title">
            <h2>{{ selectedSkill?.name || '未知技能' }}</h2>
            <div class="skill-tags">
              <el-tag :type="getCategoryType(selectedSkill?.categoryName)" size="large" effect="plain">
                {{ selectedSkill?.categoryName || '未分类' }}
              </el-tag>
              <el-tag :type="getLevelTagType(selectedSkill?.level)" size="large">
                {{ selectedSkill?.level }}
              </el-tag>
            </div>
          </div>
          <!-- <div class="skill-actions">
            <el-button size="small" :icon="Edit" @click="handleEditSkill(selectedSkill)">编辑</el-button>
          </div> -->
        </div>

        <!-- 技能基本信息 -->
        <div class="info-sections">
          <el-card class="info-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <el-icon>
                  <InfoFilled />
                </el-icon>
                <span>基本信息</span>
              </div>
            </template>

            <div class="info-grid">
              <div class="info-item">
                <label>熟练度进度</label>
                <div class="proficiency-bar">
                  <el-progress :percentage="selectedSkill?.proficiencyLevel || 0" :stroke-width="16"
                    :color="getProgressColor(selectedSkill?.proficiencyLevel)" text-inside />
                  <span class="proficiency-text">
                    {{ selectedSkill?.level }} ({{ selectedSkill?.proficiencyLevel || 0
                    }}%)
                  </span>
                </div>
              </div>

              <div class="info-item">
                <label>经验年数</label>
                <div class="info-value">
                  <el-icon>
                    <Timer />
                  </el-icon>
                  <span>{{ selectedSkill?.yearsOfExperience || 0 }} 年</span>
                </div>
              </div>

              <div class="info-item">
                <label>核心技能</label>
                <div class="info-value">
                  <el-tag :type="(selectedSkill?.isCore || 0) === 1 ? 'danger' : 'info'" size="small">
                    {{ (selectedSkill?.isCore || 0) === 1 ? '是' : '否' }}
                  </el-tag>
                </div>
              </div>

              <div class="info-item">
                <label>状态</label>
                <div class="info-value">
                  <el-tag :type="selectedSkill?.status === 'enabled' ? 'success' : 'warning'" size="small">
                    {{ selectedSkill?.status === 'enabled' ? '启用' : '禁用' }}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-card>

          <el-card class="info-card" shadow="hover" v-if="selectedSkill?.description">
            <template #header>
              <div class="card-header">
                <el-icon>
                  <Document />
                </el-icon>
                <span>技能描述</span>
              </div>
            </template>

            <div class="description-content">
              <p>{{ selectedSkill.description }}</p>
            </div>
          </el-card>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="skillDetailVisible = false">关闭</el-button>
          <!-- <el-button type="primary" @click="handleEditSkill(selectedSkill)">编辑技能</el-button> -->
        </span>
      </template>
    </el-dialog>

    <!-- 分类表单弹窗 -->
    <el-dialog v-model="categoryFormVisible" :title="categoryFormMode === 'add' ? '添加技能分类' : '编辑技能分类'" width="600px"
      @close="resetCategoryForm">
      <div class="category-form-content">
        <el-form ref="categoryFormRef" :model="categoryForm" :rules="categoryFormRules" label-width="120px" status-icon>
          <el-form-item label="分类名称" prop="name">
            <el-input v-model="categoryForm.name" placeholder="请输入分类名称" maxlength="100" show-word-limit />
          </el-form-item>

          <el-form-item label="分类描述" prop="description">
            <el-input v-model="categoryForm.description" type="textarea" :rows="3" placeholder="请描述分类的具体内容"
              maxlength="500" show-word-limit />
          </el-form-item>

          <el-form-item label="排序权重" prop="sortOrder">
            <el-input-number v-model="categoryForm.sortOrder" :min="0" :max="999" :step="1" style="width: 100%"
              controls-position="right" placeholder="数字越大越靠前" />
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-switch v-model="categoryForm.status" active-value="enabled" inactive-value="disabled" active-text="启用"
              inactive-text="禁用" />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="categoryFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCategoryForm">
            {{ categoryFormMode === 'add' ? '添加' : '更新' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus, Edit, Delete, View, Search, Refresh, InfoFilled, Timer, Document, Clock, Calendar } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { skillCategoryApi, skillApi } from '@/utils/api/index'

// 响应式数据
const activeTab = ref('categories')
const categoryLoading = ref(false)
const skillLoading = ref(false)
const isDataLoading = ref(false)

// 搜索表单
const searchForm = reactive({
  name: '',
  category: '',
  level: ''
})

// 分类搜索表单
const categorySearchForm = reactive({
  name: ''
})

// 技能分类数据
const skillCategories = ref([])

// 所有技能数据
const allSkills = ref([])

// 分页数据
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 分类分页数据
const categoryPagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 分类数据映射（用于快速查找）
const categoryMap = ref(new Map())

// 技能表单相关数据
const skillFormVisible = ref(false)
const skillFormMode = ref('add') // 'add' 或 'edit'
const skillFormRef = ref()

// 技能详情查看相关数据
const skillDetailVisible = ref(false)
const selectedSkill = ref(null)

const skillForm = reactive({
  id: null,
  name: '',
  description: '',
  categoryId: null,
  proficiencyLevel: 0,
  yearsOfExperience: 0,
  isCore: 0,
  status: 'enabled',
  sortOrder: 0
})

const skillFormRules = {
  name: [
    { required: true, message: '请输入技能名称', trigger: 'blur' },
    { min: 1, max: 100, message: '技能名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择技能分类', trigger: 'change' }
  ],
  proficiencyLevel: [
    { required: true, message: '请选择熟练度', trigger: 'change' },
    { type: 'number', min: 0, max: 100, message: '熟练度必须在0-100之间', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '技能描述长度不能超过 500 个字符', trigger: 'blur' }
  ]
}

// 分类表单相关数据
const categoryFormVisible = ref(false)
const categoryFormMode = ref('add') // 'add' 或 'edit'
const categoryFormRef = ref()

const categoryForm = reactive({
  id: null,
  name: '',
  description: '',
  sortOrder: 0,
  status: 'enabled'
})

const categoryFormRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 100, message: '分类名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '分类描述长度不能超过 500 个字符', trigger: 'blur' }
  ],
  sortOrder: [
    { type: 'number', message: '排序权重必须是数字', trigger: 'blur' }
  ]
}

// 数据结构转换函数
const transformSkillCategoryData = (backendCategory) => {
  return {
    id: backendCategory.id,
    name: backendCategory.name,
    description: backendCategory.description,
    icon: backendCategory.icon,
    color: backendCategory.color,
    sortOrder: backendCategory.sortOrder,
    status: backendCategory.status,
    skillCount: backendCategory.skillCount || 0,
    skillNameList: backendCategory.skillNameList || []
  }
}

const transformSkillData = (backendSkill) => {
  return {
    id: backendSkill.id,
    name: backendSkill.name,
    description: backendSkill.description,
    icon: backendSkill.icon,
    color: backendSkill.color,
    categoryId: backendSkill.categoryId,
    categoryName: categoryMap.value.get(backendSkill.categoryId)?.name || '未分类',
    proficiencyLevel: backendSkill.proficiencyLevel,
    yearsOfExperience: backendSkill.yearsOfExperience,
    learningTime: backendSkill.learningTime,
    level: backendSkill.level,
    remarks: backendSkill.remarks,
    sortOrder: backendSkill.sortOrder,
    isCore: backendSkill.isCore,
    status: backendSkill.status || 'enabled',
    createTime: backendSkill.createTime
  }
}

// 加载技能分类数据
const loadSkillCategories = async () => {
  try {
    categoryLoading.value = true
    isDataLoading.value = true

    const params = {}
    if (categorySearchForm.name) {
      params.name = categorySearchForm.name
    }

    const response = await skillCategoryApi.queryPage(categoryPagination.page, categoryPagination.size, params)
    if (response.code === 0) {
      const pageData = response.data
      skillCategories.value = pageData.data.map(transformSkillCategoryData)
      categoryPagination.total = pageData.total

      // 建立分类映射
      categoryMap.value = new Map(
        skillCategories.value.map(cat => [cat.id, cat])
      )
    } else {
      ElMessage.error(response.message || '加载技能分类失败')
    }
  } catch (error) {
    console.error('加载技能分类失败:', error)
    ElMessage.error('加载技能分类失败')
  } finally {
    categoryLoading.value = false
    isDataLoading.value = false
  }
}



// 加载技能数据
const loadSkills = async () => {
  try {
    skillLoading.value = true
    isDataLoading.value = true

    const params = {}
    if (searchForm.name) {
      params.name = searchForm.name
    }
    if (searchForm.category) {
      params.categoryId = searchForm.category
    }
    if (searchForm.level) {
      params.level = searchForm.level
    }

    const response = await skillApi.queryPage(pagination.page, pagination.size, params)
    if (response.code === 0) {
      const pageData = response.data
      allSkills.value = pageData.data.map(transformSkillData)
      pagination.total = pageData.total
    } else {
      ElMessage.error(response.message || '加载技能列表失败')
    }
  } catch (error) {
    console.error('加载技能列表失败:', error)
    ElMessage.error('加载技能列表失败')
  } finally {
    skillLoading.value = false
    isDataLoading.value = false
  }
}

// 生命周期钩子
onMounted(() => {
  // 加载默认显示的分类数据
  loadSkillCategories()
})

// 方法
const handleSearch = () => {
  pagination.page = 1
  loadSkills()
}

const resetSearch = () => {
  searchForm.name = ''
  searchForm.category = ''
  searchForm.level = ''
  pagination.page = 1
  loadSkills()
}

const handleCategorySearch = () => {
  categoryPagination.page = 1
  isDataLoading.value = true
  loadSkillCategories()
}

const resetCategorySearch = () => {
  categorySearchForm.name = ''
  categoryPagination.page = 1
  isDataLoading.value = true
  loadSkillCategories()
}

const handleCategorySizeChange = (size) => {
  categoryPagination.size = size
  categoryPagination.page = 1
  isDataLoading.value = true
  loadSkillCategories()
}

const handleCategoryCurrentChange = (page) => {
  categoryPagination.page = page
  isDataLoading.value = true
  loadSkillCategories()
}

const handleTabChange = (tab) => {
  if (tab === 'all') {
    // 切换到所有技能tab，加载技能数据
    if (allSkills.value.length === 0) {
      loadSkills()
    }
  } else if (tab === 'categories') {
    // 切换到分类tab，加载分类数据
    isDataLoading.value = true
    loadSkillCategories()
  }
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadSkills()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadSkills()
}

const handleAddSkill = () => {
  skillFormMode.value = 'add'
  resetSkillForm()
  skillForm.categoryId = skillCategories.value.length > 0 ? skillCategories.value[0].id : null
  skillFormVisible.value = true
}

const handleAddCategory = () => {
  categoryFormMode.value = 'add'
  resetCategoryForm()
  categoryFormVisible.value = true
}

const handleViewSkill = (skill) => {
  if (!skill) {
    ElMessage.error('技能信息不存在')
    return
  }
  selectedSkill.value = { ...skill } // 创建副本避免引用问题
  skillDetailVisible.value = true
}

const handleEditSkill = (skill) => {
  skillFormMode.value = 'edit'
  // 填充表单数据
  skillForm.id = skill.id
  skillForm.name = skill.name
  skillForm.description = skill.description || ''
  skillForm.categoryId = skill.categoryId
  skillForm.proficiencyLevel = skill.proficiencyLevel
  skillForm.yearsOfExperience = skill.yearsOfExperience || 0
  skillForm.isCore = skill.isCore || 0
  skillForm.status = skill.status || 'enabled' // 编辑时使用当前状态
  skillForm.sortOrder = skill.sortOrder || 0
  skillFormVisible.value = true
}

const handleDeleteSkill = async (skill) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除技能「${skill.name}」吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await skillApi.delete(skill.id)
    if (response.code === 0) {
      ElMessage.success('删除成功')
      loadSkillCategories()
      loadSkills()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除技能失败:', error)
      ElMessage.error('删除技能失败')
    }
  }
}

const handleEditCategory = (category) => {
  categoryFormMode.value = 'edit'
  // 填充表单数据
  categoryForm.id = category.id
  categoryForm.name = category.name
  categoryForm.description = category.description || ''
  categoryForm.sortOrder = category.sortOrder || 0
  categoryForm.status = category.status || 'enabled'
  categoryFormVisible.value = true
}

// 更新分类状态
const updateCategoryStatus = async (category) => {
  try {
    await skillCategoryApi.update(category.id, {
      name: category.name,
      description: category.description,
      icon: category.icon,
      color: category.color,
      sortOrder: category.sortOrder,
      status: category.status
    })

    // 只在非数据加载期间显示成功提示
    if (!isDataLoading.value) {
      ElMessage.success(`分类已${category.status === 'enabled' ? '启用' : '禁用'}`)
    }
  } catch (error) {
    console.error('状态更新失败:', error)
    // 如果更新失败，恢复原状态
    category.status = category.status === 'enabled' ? 'disabled' : 'enabled'
    // 只在非数据加载期间显示错误提示
    if (!isDataLoading.value) {
      ElMessage.error('状态更新失败')
    }
  }
}

// 更新技能状态
const updateSkillStatus = async (skill) => {
  try {
    await skillApi.update(skill.id, {
      name: skill.name,
      description: skill.description,
      categoryId: skill.categoryId,
      proficiencyLevel: skill.proficiencyLevel,
      yearsOfExperience: skill.yearsOfExperience,
      sortOrder: skill.sortOrder,
      isCore: skill.isCore,
      status: skill.status
    })

    // 只在非数据加载期间显示成功提示
    if (!isDataLoading.value) {
      ElMessage.success(`技能已${skill.status === 'enabled' ? '启用' : '禁用'}`)
    }
  } catch (error) {
    console.error('技能状态更新失败:', error)
    // 如果更新失败，恢复原状态
    skill.status = skill.status === 'enabled' ? 'disabled' : 'enabled'
    // 只在非数据加载期间显示错误提示
    if (!isDataLoading.value) {
      ElMessage.error('技能状态更新失败')
    }
  }
}

const handleDeleteCategory = async (category) => {
  try {
    // 显示警告信息
    await ElMessageBox.confirm(
      `确定要删除分类「${category.name}」吗？这将同时删除该分类下的 ${category.skillCount} 个技能。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 调用后端接口删除分类
    const response = await skillCategoryApi.delete(category.id)
    if (response.code === 0) {
      ElMessage.success(`分类「${category.name}」删除成功`)
      loadSkillCategories()
    } else {
      ElMessage.error(response.message || '删除分类失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分类失败:', error)
      ElMessage.error('删除分类失败')
    }
  }
}

// 工具函数
const getCategoryType = (categoryName) => {
  const types = {
    '前端开发': '',
    '后端开发': 'success',
    '数据库': 'warning',
    '工具和部署': 'info'
  }
  return types[categoryName] || ''
}

const getLevelTagType = (level) => {
  if (!level) return 'info'
  const typeMap = {
    '入门': 'info',
    '初级': 'primary',
    '中级': 'success',
    '高级': 'warning',
    '专家': 'danger'
  }
  return typeMap[level] || 'info'
}

const getProgressColor = (level) => {
  if (!level) return '#909399'
  const colorMap = {
    '入门': '#909399',
    '初级': '#409EFF',
    '中级': '#67C23A',
    '高级': '#E6A23C',
    '专家': '#F56C6C'
  }
  return colorMap[level] || '#909399'
}

// 表单方法
const submitSkillForm = async () => {
  if (!skillFormRef.value) return

  try {
    await skillFormRef.value.validate()

    const apiData = {
      name: skillForm.name.trim(),
      description: skillForm.description?.trim() || '',
      categoryId: skillForm.categoryId,
      proficiencyLevel: skillForm.proficiencyLevel,
      yearsOfExperience: skillForm.yearsOfExperience || 0,
      sortOrder: skillForm.sortOrder || 0,
      isCore: skillForm.isCore || 0,
      status: skillForm.status || 'enabled'
    }

    let response
    if (skillFormMode.value === 'add') {
      response = await skillApi.create(apiData)
    } else {
      response = await skillApi.update(skillForm.id, apiData)
    }

    if (response.code === 0) {
      ElMessage.success(skillFormMode.value === 'add' ? '添加技能成功' : '更新技能成功')
      skillFormVisible.value = false
      loadSkills()

      // 如果是新增且当前在分类页面，也要刷新分类数据
      if (skillFormMode.value === 'add') {
        loadSkillCategories()
      }
    } else {
      ElMessage.error(response.message || (skillFormMode.value === 'add' ? '添加技能失败' : '更新技能失败'))
    }
  } catch (error) {
    console.error('提交技能表单失败:', error)
    if (error !== false) { // 验证失败时不显示错误
      ElMessage.error(skillFormMode.value === 'add' ? '添加技能失败' : '更新技能失败')
    }
  }
}

const resetSkillForm = () => {
  if (skillFormRef.value) {
    skillFormRef.value.resetFields()
  }

  skillForm.id = null
  skillForm.name = ''
  skillForm.description = ''
  skillForm.categoryId = null
  skillForm.proficiencyLevel = 0
  skillForm.yearsOfExperience = 0
  skillForm.isCore = 0
  skillForm.status = 'enabled'
  skillForm.sortOrder = 0
}

// 分类表单方法
const submitCategoryForm = async () => {
  if (!categoryFormRef.value) return

  try {
    await categoryFormRef.value.validate()

    const apiData = {
      name: categoryForm.name.trim(),
      description: categoryForm.description?.trim() || '',
      sortOrder: categoryForm.sortOrder || 0,
      status: categoryForm.status || 'enabled'
    }

    let response
    if (categoryFormMode.value === 'add') {
      response = await skillCategoryApi.create(apiData)
    } else {
      response = await skillCategoryApi.update(categoryForm.id, {
        ...apiData,
        id: categoryForm.id
      })
    }

    if (response.code === 0) {
      ElMessage.success(categoryFormMode.value === 'add' ? '添加分类成功' : '更新分类成功')
      categoryFormVisible.value = false
      loadSkillCategories()
    } else {
      ElMessage.error(response.message || (categoryFormMode.value === 'add' ? '添加分类失败' : '更新分类失败'))
    }
  } catch (error) {
    console.error('提交分类表单失败:', error)
    if (error !== false) { // 验证失败时不显示错误
      ElMessage.error(categoryFormMode.value === 'add' ? '添加分类失败' : '更新分类失败')
    }
  }
}

const resetCategoryForm = () => {
  if (categoryFormRef.value) {
    categoryFormRef.value.resetFields()
  }

  categoryForm.id = null
  categoryForm.name = ''
  categoryForm.description = ''
  categoryForm.sortOrder = 0
  categoryForm.status = 'enabled'
}
</script>

<style scoped>
.skills-page {
  padding: 0;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 20px;
}

/* 表格头部样式 */
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.action-buttons {
  display: flex;
  gap: 1px;
  align-items: center;
}

.action-buttons .el-button {
  flex-shrink: 0;
}



.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

.el-dialog {
  border-radius: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 技能详情弹窗样式 */
.skill-detail-content {
  padding: 0;
  max-height: calc(90vh - 140px);
  /* 90%视口高度减去弹窗头部和尾部高度 */
  overflow-y: auto;
  /* 内容区域滚动，弹窗本身不滚动 */
  overflow-x: hidden;
  /* 防止水平滚动 */
}

.skill-form-content {
  max-height: calc(80vh - 180px);
  /* 表单弹窗内容最大高度 */
  overflow-y: auto;
  /* 表单内容可以滚动 */
  overflow-x: hidden;
  /* 防止水平滚动 */
  padding-right: 4px;
  /* 为滚动条预留空间 */
}

.skill-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.skill-title h2 {
  margin: 0 0 12px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.skill-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.skill-actions {
  flex-shrink: 0;
}

.info-sections {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
  font-size: 16px;
}

.card-header .el-icon {
  color: #409EFF;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.info-value {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 16px;
  color: #303133;
}

.proficiency-bar {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.proficiency-text {
  font-size: 14px;
  color: #606266;
  margin-left: 8px;
}

.description-content {
  color: #303133;
  line-height: 1.6;
  font-size: 14px;
}

.description-content p {
  margin: 0;
  white-space: pre-wrap;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }

  .skill-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .skill-actions {
    align-self: flex-end;
  }
}
</style>